//
//  SYDProduceProgressViewController.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/8/8.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "SYDProduceProgressViewController.h"
#import "SYDPasswordPayment.h"
@interface SYDProduceProgressViewController ()<UITextFieldDelegate,PayWordViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *bandCardTextField;
@property (weak, nonatomic) IBOutlet UITextField *withdrawMoney;
@property (weak, nonatomic) IBOutlet UILabel *walletMoneyLbl;
@property (weak, nonatomic) IBOutlet UIButton *allDrawBtn;
@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;
@property (weak, nonatomic) IBOutlet UILabel *moneyStatusLbl;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConstraint;

@property (nonatomic, strong) UIView *maskView;//遮罩View
@property (nonatomic, strong) SYDPasswordPayment *passwordView;

@property(nonatomic,strong)NSString *payCode;//支付密码

@end

@implementation SYDProduceProgressViewController
#pragma mark - 导航栏
- (void)navigationBarHandle{
    
    // 导航栏返回按钮
    WEAKSELF
    [self backButtonAction:^{
        
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
}
#pragma mark---根据userId获取个人账号信息
-(void)getMinePayCode{
    WEAKSELF
    [[SYDNetwork shareTool]getMineAcountWithUserId:[YMSaveTool valueForKey:USER_ID] success:^(NSURLSessionDataTask *task, id responseObject) {
        @try {
            if ([responseObject[@"statusCode"]integerValue] == 200) {
                weakSelf.payCode = [responseObject[@"obj"]valueForKey:@"payCode"];
            }
        } @catch (NSException *exception) {
            NSLog(@"---%@",exception.description);
        } @finally {
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (iPhone8_X) {
        self.topConstraint.constant = 88;
    } else {
        self.topConstraint.constant = 64;
    }
    [self getMinePayCode];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationBar.title = @"个人资料";
    [self navigationBarHandle];
    [self initProgressUI];
}
-(void)initProgressUI{
    
    self.bandCardTextField.delegate = self;
//    self.bandCardTextField.placeholderColor = GRAY_COLOR;
    self.bandCardTextField.textColor = TABBAR_COLOR;
    self.bandCardTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.bandCardTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.bandCardTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.bandCardTextField.keyboardAppearance=UIKeyboardAppearanceDefault;
    self.bandCardTextField.returnKeyType = UIReturnKeyNext;
    
    self.withdrawMoney.delegate = self;
//    self.withdrawMoney.placeholderColor = GRAY_COLOR;
    self.withdrawMoney.textColor = TITLE_COLOR;
    self.withdrawMoney.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.withdrawMoney.keyboardType = UIKeyboardTypeDecimalPad;
    self.withdrawMoney.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.withdrawMoney.keyboardAppearance=UIKeyboardAppearanceDefault;
    self.withdrawMoney.returnKeyType = UIReturnKeyDone;
    self.walletMoneyLbl.text = self.walletModel.balance;
    WEAKSELF
    [[self.allDrawBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        weakSelf.withdrawMoney.text = [weakSelf.walletModel.balance stringByAppendingString:@"元"];
    }];
    [self.confirmBtn drawBorderWithColor:GREEN_COLOR radius:5];
    self.confirmBtn.eventTimeInterval = 3.0;
    [[self.confirmBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf.bandCardTextField resignFirstResponder];
        [weakSelf.withdrawMoney resignFirstResponder];
        if (![NSString IsBankCard:weakSelf.bandCardTextField.text]) {
            [SVProgressHUD displayInfoWithStatus:@"银行卡号码不合法"];
        }else if (!([weakSelf.withdrawMoney.text floatValue] >= 0)){
            [SVProgressHUD displayInfoWithStatus:@"提现金额不符合规则"];
        }else if (weakSelf.withdrawMoney.text.length == 0){
            [SVProgressHUD displayInfoWithStatus:@"请输入提现金额"];
        }else{
            //先判断有没有设置支付密码  1.没有设置支付密码,需要去设置  2。设置唤醒弹窗  进行密码支付
            if ([weakSelf.payCode isEqualToString:@""]||[weakSelf.payCode isEqual:nil]) {//需要去设置支付密码
                SYDSetThepaymentController *setPayVc = [[SYDSetThepaymentController alloc]init];
                [weakSelf.navigationController pushViewController:setPayVc animated:YES];
            }else{
                [weakSelf.view addSubview:weakSelf.maskView];
                [weakSelf.view addSubview:weakSelf.passwordView];
            }
        }
    }];

    // 点击遮罩层
    [self.maskView jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [weakSelf removeMaskOrPopup];
    }];
    self.passwordView.closeBlock = ^{
        [weakSelf removeMaskOrPopup];
    };
    self.passwordView.forgetBlock = ^{
        SYDRetrievePayPasswordController *retrievePayVc = [[SYDRetrievePayPasswordController alloc]init];
        [weakSelf.navigationController pushViewController:retrievePayVc animated:YES];
    };
#pragma mark---监听textfield 输入文字
    [self.bandCardTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        NSLog(@"银行卡号:%@",x);
        if (x.length >= 24) {
            return;
        } else {
            
        }
    }];

    [self.withdrawMoney.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        NSLog(@"提现:%@",x);
        if ([x floatValue] > [weakSelf.walletModel.balance floatValue]) {
            [SVProgressHUD displayInfoWithStatus:@"提现金额大于当前钱包余额"];
            self.moneyStatusLbl.text = @"输入金额超过零钱余额";
            self.moneyStatusLbl.textColor = RED_COLOR;
            self.walletMoneyLbl.hidden = YES;
        }else{
            self.moneyStatusLbl.text = @"可提现余额";
            self.moneyStatusLbl.textColor = GRAY_COLOR;
            self.walletMoneyLbl.text = [weakSelf.walletModel.balance stringByAppendingString:@"元"];
            self.walletMoneyLbl.hidden = NO;
        }
    }];

}

#pragma mark---PayWordViewDelegate
-(void)passwordTextFieldChanged:(NSString *)textfieldValue{
    NSLog(@"textfieldValue:%@",textfieldValue);
    self.payCode = textfieldValue;
    WEAKSELF
    [[SYDNetwork shareTool]paycodeValidationWithCityCode:[YMSaveTool valueForKey:CityCode] payCode:textfieldValue userId:[YMSaveTool valueForKey:USER_ID] success:^(NSURLSessionDataTask *task, id responseObject) {
        @try {
            NSLog(@"----responseObject:%@",responseObject);
            if ([responseObject[@"statusCode"]integerValue] == 200) {
            
                [weakSelf removeMaskOrPopup];
                SYDMentionDetailsController *mentionDetailsVc = [[SYDMentionDetailsController alloc]init];
                mentionDetailsVc.bankCard = weakSelf.bandCardTextField.text;
                mentionDetailsVc.amount = weakSelf.withdrawMoney.text;
                [weakSelf.navigationController pushViewController:mentionDetailsVc animated:YES];
            } else {
                [weakSelf.passwordView clearUpPassword];//清除密码
                [SVProgressHUD displayInfoWithStatus:responseObject[@"msg"] time:1.5f];
            }
        } @catch (NSException *exception) {
            NSLog(@"%@",exception.description);
        } @finally {
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error.description);
    }];
}
#pragma UITextFieldDelegate实现输入四位数出现一个空格
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.bandCardTextField) {
        NSString *text = [textField text];
        NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
        string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
        if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
            return NO;
        }
        text = [text stringByReplacingCharactersInRange:range withString:string];
        text = [text stringByReplacingOccurrencesOfString:@" "withString:@""];
        if ([text length] >= 21) {
            return NO;
        }
        
        NSString *newString =@"";
        while (text.length >0) {
            NSString *subString = [text substringToIndex:MIN(text.length,4)];
            newString = [newString stringByAppendingString:subString];
            if (subString.length ==4) {
                newString = [newString stringByAppendingString:@" "];
            }
            text = [text substringFromIndex:MIN(text.length,4)];
        }
        newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
        [textField setText:newString];
        return NO;
    }
    return  YES;
}
// 移除遮罩层和弹窗
- (void)removeMaskOrPopup{
    
    [self.passwordView removeFromSuperview];
    
    [self.maskView removeFromSuperview];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
- (UIView *)maskView{
    if (!_maskView) {
        _maskView = [[UIView alloc] initWithFrame:SCREEN_RECT];
        _maskView.backgroundColor = [UIColor blackColor];
        _maskView.alpha = 0.3;
    }
    return _maskView;
}
-(SYDPasswordPayment *)passwordView{
    if (!_passwordView) {
        _passwordView = [[SYDPasswordPayment alloc]initWithFrame:CGRectMake(0, self.view.centerY-64, SCREEN_WIDTH, 150)];
        _passwordView.delegate = self;
    }
    return _passwordView;
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
